package com.weibei.common.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.weibei.common.utils.wx.WXPayUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.util.*;

/**
 * @author daixilong
 * @version 1.0.0
 * @ClassName SignCheckUtils.java
 * @Description TODO 对参数签名的校验
 * @Date 2021/5/30 12:06
 */
@Slf4j
public  class ParamCheckUtils {

    public static final String SIGN="sign";

    private ParamCheckUtils(){}


    @SneakyThrows
    public static boolean isvalid(Object obj, String key){
        Map map = BeanUtil.beanToMap(obj);
        if (!map.containsKey(SIGN)) {
            return false;
        }
        if(Objects.isNull(map.get(SIGN))){
            return false;
        }
        log.info("签名入参：{}", JSONUtil.toJsonStr(map));
        String s = sign(map,key);
        if (Objects.isNull(s)) {
            return false;
        }
        log.info("sign:{}",s);
        return map.get(SIGN).equals(s);
    }

    public static String sign(Map<String,Object> data,String key){
        Map<String,Object> map=data;
        if(map.containsKey(SIGN)){
            map.remove(SIGN);
        }
        if (CollectionUtil.isEmpty(map)) {
            return null;
        }
        Set<String> keySet = map.keySet();
        String[] keyArray = keySet.toArray(new String[keySet.size()]);
        Arrays.sort(keyArray);
        StringBuilder sb=new StringBuilder();
        for (String k : keyArray) {
            if (Objects.nonNull(map.get(k)) && map.get(k).toString().trim().length() > 0){
                // 参数值为空，则不参与签名
                sb.append(k).append("=").append(map.get(k).toString().trim()).append("&");
            }
        }
        if (sb.length()<=0) {
            return null;
        }
        sb.append("key=").append(key);
        try {
            return WXPayUtil.MD5(sb.toString()).toUpperCase();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("MD5方法错误：{}",e.getMessage());
            return null;
        }
    }
}
